package com.weixing.mall.provider.controller.front;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.enums.SysCfgCodeEnum;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.base.enums.IsEnableEnum;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.MemAuth;
import com.weixing.mall.core.support.auth.MemInfo;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.api.model.vo.AgentVo;
import com.weixing.mall.provider.api.model.vo.SysConfigVo;
import com.weixing.mall.provider.api.service.MemberServiceRpc;
import com.weixing.mall.provider.api.service.SysConfigServiceFeign;
import com.weixing.mall.provider.model.domain.Agent;
import com.weixing.mall.provider.model.domain.AgentBonusGroup;
import com.weixing.mall.provider.model.dto.AgentRePwdDto;
import com.weixing.mall.provider.model.vo.AgentGroupVo;
import com.weixing.mall.provider.api.model.vo.FrontAgentTreeVo;
import com.weixing.mall.provider.model.vo.AgentTreeVo;
import com.weixing.mall.provider.service.IAgentBonusGroupService;
import com.weixing.mall.provider.service.IAgentService;
import com.weixing.mall.util.regex.RegexUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kfc
 * @Title: ${FrontAgentController}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2019/11/115:40
 */
@RestController
@RequestMapping("front/agent")
@Validated
@Api(value = "前端:代理商", tags = "前端:代理商")
public class FrontAgentController extends BaseController {
    @Autowired
    private IAgentService agentService;
    @Autowired
    private IAgentBonusGroupService agentBonusGroupService;
    @Autowired
    private SysConfigServiceFeign sysConfigServiceFeign;
    @Autowired
    private MemberServiceRpc memberServiceRpc;


    @ApiOperation(value = "根据代理商手机号或者代理商优惠id查询代理商")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "searchParam", value = "手机号/优惠id", paramType = "form", dataType = "string")
    })
    @NoNeedAccess
    @GetMapping("bindSearch")
    public Result<AgentVo> index(@NotNull(message = "查询条件不能为空") String searchParam) {
        AgentVo agentVo = null;
        if (RegexUtil.isMobile(searchParam)) {
            agentVo = agentService.selectByMobile(searchParam);
        } else {
            agentVo = agentService.selectByAgentSn(searchParam);
        }
        // 限制条件
        if (null == agentVo) {
            return ResultUtil.error("代理商不存在");
        } else {
            if (IsEnableEnum.DISABLE.getValue().equals(agentVo.getIsEnable()) ||
                    DateUtil.compare(new Date(), agentVo.getMaturityTime()) > 0
            ) {
                return ResultUtil.error("代理商不可用，或已过期");
            }
        }

        if (WhetherEnum.NO == agentVo.getIsBind()) {
            return ResultUtil.error("该代理尚未绑定结构树，暂不可用");
        }
        return ResultUtil.success(agentVo);
    }

    @ApiOperation(value = "代理等级结构树")
    @GetMapping("tree")
    public Result tree(@MemInfo MemAuth auth) {
        int total = 1;
        Agent agent = agentService.getById(auth.getAbid());
        FrontAgentTreeVo frontAgentTreeVo = new FrontAgentTreeVo();
        frontAgentTreeVo.setId(agent.getId());
        frontAgentTreeVo.setAgentName(agent.getAgentName());
        frontAgentTreeVo.setAgentSn(agent.getAgentSn());
        frontAgentTreeVo.setAgentLevel(EnumUtil.getDesp(AgentLevelEnum.class, agent.getAgentLevel()));
        wrapperTree(agent, frontAgentTreeVo, total);
        return ResultUtil.success(frontAgentTreeVo);
    }

    /**
     * 我的团队
     *
     * @return  团队
     */
    @GetMapping("group")
    public Result<AgentGroupVo> group() {
        MemAuth auth = AuthUtil.getMemberExt();
        Agent agent = agentService.getById(auth.getAbid());

        AgentGroupVo agentGroupVo = new AgentGroupVo();
        List<FrontAgentTreeVo> partnerGroup = Lists.newArrayList();
        List<FrontAgentTreeVo> invalidGroup = Lists.newArrayList();

        FrontAgentTreeVo frontAgentTreeVo = new FrontAgentTreeVo();
        frontAgentTreeVo.setId(agent.getId());
        frontAgentTreeVo.setAgentName(agent.getAgentName());
        frontAgentTreeVo.setAgentSn(agent.getAgentSn());
        frontAgentTreeVo.setMobile(agent.getMobile());
        frontAgentTreeVo.setAgentLevel(EnumUtil.getDesp(AgentLevelEnum.class, agent.getAgentLevel()));
        wrapperGroup(agent, frontAgentTreeVo, invalidGroup);
        // 无效
        agentGroupVo.setInvalidGroupTotal(invalidGroup.size());
        agentGroupVo.setInvalidGroup(invalidGroup);
        // 团队
        // 团队人数
        int cnt = agentService.countGroupPerson(agent);
        agentGroupVo.setGroupTotal(cnt);
        agentGroupVo.setGroupTree(frontAgentTreeVo);
        // 合伙
        List<AgentBonusGroup> agentBonusGroup = agentBonusGroupService.findByObliee(agent.getId());
        if (CollUtil.isNotEmpty(agentBonusGroup)) {
            List<Long> ids = Lists.newArrayList();
            for (AgentBonusGroup group : agentBonusGroup) {
                ids.add(group.getAgentId());
            }
            List<Agent> agents = (List<Agent>) agentService.listByIds(ids);
            FrontAgentTreeVo vo = null;
            for (Agent at : agents) {
                vo = getFrontAgentTreeVo(at);
                partnerGroup.add(vo);
            }
        }
        agentGroupVo.setPartnerGroup(partnerGroup);
        agentGroupVo.setPartnerGroupTotal(partnerGroup.size());
        return ResultUtil.success(agentGroupVo);
    }

    private void wrapperGroup(Agent agent, FrontAgentTreeVo parentVo, List<FrontAgentTreeVo> invalidGroup) {
        List<Agent> children = agentService.findByParentId(agent.getId());
        if (CollUtil.isNotEmpty(children)) {
            List<FrontAgentTreeVo> childs = Lists.newArrayList();
            FrontAgentTreeVo childVo = null;
            for (Agent agentChild : children) {
                childVo = getFrontAgentTreeVo(agentChild);
                childs.add(childVo);
                if (IsEnableEnum.DISABLE.getValue().equals(agentChild.getIsEnable())) {
                    invalidGroup.add(childVo);
                }
                wrapperGroup(agentChild, childVo, invalidGroup);
            }
            parentVo.setChildren(childs);
        }
    }

    private FrontAgentTreeVo getFrontAgentTreeVo(Agent agentChild) {
        FrontAgentTreeVo childVo = new FrontAgentTreeVo();
        childVo.setId(agentChild.getId());
        childVo.setAgentName(agentChild.getAgentName());
        childVo.setAgentSn(agentChild.getAgentSn());
        childVo.setMobile(agentChild.getMobile());
        childVo.setAgentLevel(EnumUtil.getDesp(AgentLevelEnum.class, agentChild.getAgentLevel()));
        return childVo;
    }


    private void wrapperTree(Agent agent, FrontAgentTreeVo parentVo, int total) {
        List<Agent> children = agentService.findByParentId(agent.getId());
        if (CollUtil.isNotEmpty(children)) {
            total = total + children.size();
            List<FrontAgentTreeVo> childs = Lists.newArrayList();
            FrontAgentTreeVo childVo = null;
            for (Agent agentChild : children) {
                childVo = getFrontAgentTreeVo(agentChild);
                childs.add(childVo);
                wrapperTree(agentChild, childVo, total);
            }
            parentVo.setChildren(childs);
            parentVo.setTotal(total);
        }
    }

    @ApiOperation(value = "代理商信息")
    @GetMapping("agentInfo")
    public Result agentInfo(@MemInfo MemAuth auth) {
        Result<SysConfigVo> voResult = sysConfigServiceFeign.getByCode(SysCfgCodeEnum.AGENT_EXPIRE_ALERT.getCode());
        if (!voResult.isSuccess()) {
            return voResult;
        }
        SysConfigVo data = voResult.getData();
        int eDay = data.getCfgValue();
        Agent agent = agentService.getById(auth.getAbid());
        Integer isEnable = agent.getIsEnable();
        if (IsEnableEnum.DISABLE.getValue().equals(isEnable)) {
            return ResultUtil.error("您已被已禁用");
        }
        Date now = new Date();
        Date effectTime = agent.getEffectTime();
        if (now.before(effectTime)) {
            return ResultUtil.error("您的代理权益还未生效！");
        }
        Date maturityTime = agent.getMaturityTime();
        if (now.after(maturityTime)) {
            return ResultUtil.error("您的代理权益有效期已过，请联系您的专属客服续费！");
        }
        long between = DateUtil.between(now, maturityTime, DateUnit.DAY);
        if (between < eDay) {
            return ResultUtil.success(ResultCodeEnum.CODE_10015001, String.valueOf(between));
        }
        Map<String, Object> returnVo = new HashMap<>();
        if (agent != null) {
            returnVo.put("sn", agent.getAgentSn());//代理商编码
            returnVo.put("level", EnumUtil.getDesp(AgentLevelEnum.class, agent.getAgentLevel()));//代理商等级
            returnVo.put("name", agent.getAgentName());//代理商名称
            returnVo.put("type", agent.getAgentType());//代理商类型 0金级，1银级
            returnVo.put("isOfficial", agent.getIsOfficial());//代理商性质 0试用，1正式
            returnVo.put("maturityTime", DateUtil.formatDateTime(agent.getMaturityTime()));//代理商到期时间
            returnVo.put("discount", agent.getDiscount());//个人折扣
            returnVo.put("customerName", agent.getCustomerName());//所属客服名称
            returnVo.put("dealer", agent.getDealer());//所属经销商名称
        }
        return ResultUtil.success(returnVo);
    }

    @ApiOperation(value = "重置密码")
    @GetMapping("resetPwd")
    public Result resetPwd(@Validated AgentRePwdDto dto) {
        MemAuth memberExt = AuthUtil.getMemberExt();
        Long abid = memberExt.getAbid();
        Agent byId = agentService.getById(abid);
//        if (!CommonUtil.bCryptCheck(dto.getOldPwd(), byId.getPassword())) {
//            return ResultUtil.error("旧密码验证失败");
//        }
        byId.setPassword(CommonUtil.encryptPassword(dto.getNewPwd()));

        agentService.resetPwd(byId,dto.getNewPwd());
        return ResultUtil.success();
    }
    @ApiOperation(value = "获取前10个团队数量")
    @GetMapping("getTopten")
    @NoNeedAccess
    public  Result getTop10AgentTeam(){
       List<AgentTreeVo> agentGroupVoList =agentService.getTop10AgentTeam();
        return ResultUtil.success(agentGroupVoList);
    }

}
